package org.example.erpdemo.demos.controller;

import org.example.erpdemo.demos.model.SaleOrder;
import org.example.erpdemo.demos.model.SaleOrderLine;
import org.example.erpdemo.demos.service.SaleOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class SaleOrderController {

    @Autowired
    private SaleOrderService saleOrderService;

    @PostMapping("/sign-in")
    public String signIn(String username, String password, HttpSession session) {
        // 简单的登录验证逻辑
        if ("admin".equals(username) && "admin".equals(password)) {
            session.setAttribute("session_user_key", 1);
            return "登录成功";
        }
        return null;
    }

    @PostMapping("/inbound/create")
    public ResponseEntity<?> createInboundOrder(@RequestBody Map<String, Object> request) {
        Map<String, Object> orderMap = (Map<String, Object>) request.get("order");
        List<Map<String, Object>> lines = (List<Map<String, Object>>) request.get("lines");

        SaleOrder order = new SaleOrder();
        order.setId(UUID.randomUUID().toString()); // 生成ID
        order.setRemark((String) orderMap.getOrDefault("remark", "Default Remark"));

        List<SaleOrderLine> orderLines = new ArrayList<>();
        for (Map<String, Object> line : lines) {
            SaleOrderLine orderLine = new SaleOrderLine();
            orderLine.setId(UUID.randomUUID().toString());
            orderLine.setMaterial((String) line.get("part"));
            orderLine.setQty(BigDecimal.valueOf((Double) line.get("actualQty")));
            orderLines.add(orderLine);
        }

        saleOrderService.createSaleOrder(order, orderLines);
        return ResponseEntity.ok("订单创建成功");
    }
}
